package netWork.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient() throws IOException {
        socket = new Socket("127.0.0.1", 8080);
    }

    public void start(){
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while(true){
                System.out.print("> ");
                String request = scanner.next();

                printWriter.println(request);
                printWriter.flush();

                if(!scannerNet.hasNext()){
                    System.out.println("服务端断开链接！");
                    break;
                }

                String response = scannerNet.next();
                System.out.println(response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient();

        tcpEchoClient.start();
    }
}
